<?php

namespace App\Http\Controllers\Wechat;

use App\Models\Mission;
use App\Models\UserWallet;
use App\Models\WechatUser;
use App\Http\Controllers\Controller;
use App\Business\BLL\Wechat\WechatPayment;
use function EasyWeChat\Kernel\Support\generate_sign;

class PayController extends Controller
{
    public function pay()
    {
        $userId = request()->input('user_id', 0);
        $qty = request()->input('qty', 1);

        //查询用户信息
        $user = WechatUser::find($userId);
        if (!$userId) {
            return response()->json(["recode" => 0, "msg" => '用户不存在']);
        }

        $ordNo = $userId.time();

        //产生充值记录
        $mission = new Mission;
        $mission->user_id = $userId;
        $mission->qty = $qty;
        $mission->type = 'recharge';
        $mission->ord_no = $ordNo;
        $mission->status = 0;
        $mission->save();
        
        //回调url
        $notifyUrl = route('wechat.pay.callback');

        $app = WechatPayment::make();

        $jssdk = $app->jssdk;

        $result = $app->order->unify([
            'body' => '乒乓币充值',
            'out_trade_no' => $ordNo,
            'trade_type' => 'JSAPI',
            'openid' => $user->openid,
            'total_fee' => $qty,
            'notify_url' => $notifyUrl,
        ]);
        if ($result['return_code'] === 'SUCCESS'){
            $prepayId = $result['prepay_id'];
            $params = $jssdk->sdkConfig($prepayId);
            return response()->json(["recode" => 1, "params" => $params]);
        }else{
            return response()->json(["recode" => 0, "msg" => $result]);
        }
    }

    public function callback()
    {
        $app = WechatPayment::make();

        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            // $recharge = Mission::find($message['out_trade_no']);
            $recharge = Mission::where('ord_no',$message['out_trade_no'])->first();

            if (!$recharge || $recharge->status == 1) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $recharge->status = 1;
                    //更新数量
                    $userWallet = UserWallet::firstOrNew (
                        ['user_id' => $recharge->user_id], ['money' => 0]
                    );
                    $userWallet->money += $recharge->qty;
                    $userWallet->save(); //更新乒乓币数量
                    $recharge->save(); // 保存订单
                    // 用户支付失败
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        return $response;
    }
}
